package com.jlsoft;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import com.ums.AppHelper;
import com.ums.upos.sdk.exception.CallServiceException;
import com.ums.upos.sdk.exception.SdkException;
import com.ums.upos.sdk.scanner.OnScanListener;
import com.ums.upos.sdk.scanner.ScannerManager;
import com.ums.upos.sdk.system.BaseSystemManager;
import com.ums.upos.sdk.system.OnServiceStatusListener;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * This class echoes a string called from JavaScript.
 */
public class UPosPlugin extends CordovaPlugin {
  public static CallbackContext ctx = null;
  private final ScannerManager scannerManager = new ScannerManager();

  private static boolean isLogin = false;

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    ctx = callbackContext;
    JSONObject obj = args.getJSONObject(0);
    Log.d("UPosPlugin", "执行调用方法:" + action + " 输入参数:" + obj.toString());
    String filePath;
    if (action.equals("CallTrans")) {
      filePath = obj.getString("AppName");
      String bizName = obj.getString("BizName");
      JSONObject transData = obj.getJSONObject("TransData");
      Intent intent = JLAppHelper.callTrans(this.cordova.getActivity(), filePath, bizName, transData);
      this.cordova.startActivityForResult(this, intent, 1000);

//          JSONObject jObj = new JSONObject();
//          jObj.put("amt",0.01);
//          jObj.put("isNeedPrintReceipt",true);
//          jObj.put("tradeType","useScan");
//          jObj.put("code","");
//          Intent intent = JLAppHelper.callTrans(this.cordova.getActivity(),"POS 通","POS通",jObj);
//          this.cordova.startActivityForResult(this, intent, 1000);

      return true;
    } else if (action.equals("CallPrint")) {
      filePath = obj.getString("FilePath");
//          AppHelper.callPrint(this.cordova.getActivity(), filePath);
      Intent intent = JLAppHelper.callPrint(this.cordova.getActivity(), filePath);
      this.cordova.startActivityForResult(this, intent, 1000);
      return true;
    } else if (action.equals("CallPrint")) {
      return true;
    } else if (action.equals("CallScanner")) {
      startScanner(callbackContext);
      return true;
    } else {
      callbackContext.error("不支持的调用功能");
      return false;
    }
  }

  //  @Override
  public boolean execute1(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    ctx = callbackContext;
    if (action.equals("coolMethod")) {
      String message = args.getString(0);
      this.coolMethod(message, callbackContext);
      return true;
    }
    return false;
  }

  private void coolMethod(String message, CallbackContext callbackContext) throws JSONException {
    if (message != null && message.length() > 0) {

      JSONObject jo = new JSONObject();
      jo.put(AppHelper.TRANS_APP_NAME, "POS 通");
      jo.put(JLAppHelper.TRANS_BIZ_ID, "POS 通");
      JSONObject jObj = new JSONObject();
      jObj.put("amt", 0.01);
      jObj.put("isNeedPrintReceipt", true);
      jObj.put("tradeType", "useScan");
      jObj.put("code", "");
      jo.put(JLAppHelper.TRANS_DATA, jObj);
      Intent intent = JLAppHelper.callTrans(this.cordova.getActivity(), "银行卡收款", "消费", jObj);
//			callbackContext.success(message);
      this.cordova.startActivityForResult(this, intent, 1000);
      //callbackContext.success(message);
    } else {
      callbackContext.error("Expected one non-empty string argument.");
    }
  }

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (JLAppHelper.TRANS_REQUEST_CODE == requestCode) {
      if (Activity.RESULT_OK == resultCode) {
        if (null != data) {
          JSONObject jo = new JSONObject();
          Map<String, String> map = JLAppHelper.filterTransResult(data);
          try {
            jo.put(JLAppHelper.TRANS_APP_NAME, map.get(JLAppHelper.TRANS_APP_NAME));
            jo.put(JLAppHelper.TRANS_BIZ_ID, map.get(JLAppHelper.TRANS_BIZ_ID));
            jo.put(JLAppHelper.RESULT_CODE, map.get(JLAppHelper.RESULT_CODE));

            String transData = map.get(JLAppHelper.TRANS_DATA);
            JSONObject jObj = new JSONObject(transData);
            jo.put(JLAppHelper.TRANS_DATA, jObj);
            ctx.success(jo);
          } catch (JSONException e) {
            e.printStackTrace();
            ctx.error("调用成功但发生异常:" + e.getMessage());
          }
        } else {
          ctx.error("调用成功但无回传数据");
        }
      } else {
        ctx.error("调用失败..");
      }
    } else if (JLAppHelper.PRINT_REQUEST_CODE == requestCode) {
      if (Activity.RESULT_OK == resultCode) {
        if (null != data) {
          JSONObject jo = new JSONObject();
          String printCode = data.getStringExtra("resultCode");
          try {
            jo.put(JLAppHelper.RESULT_CODE, printCode);
            ctx.success(jo);
          } catch (JSONException e) {
            e.printStackTrace();
            ctx.error("调用成功但出现异常:" + e.getMessage());
          }
        } else {
          ctx.error("调用成功但无数据返回");
        }
      } else {
        ctx.error("调用失败");
      }
    }
  }

  /**
   * 开始调用王府井扫码接口
   *
   * @param callbackContext
   */
  private void startScanner(final CallbackContext callbackContext) {
    try {
      BaseSystemManager.getInstance().deviceServiceLogin(this.cordova.getActivity(), null, "99999998", new OnServiceStatusListener() {
        @Override
        public void onStatus(int i) {
          if (0 == i || 2 == i || 100 == i) {

            try {
              UPosPlugin.this.scannerManager.startScan(6000, new OnScanListener() {
                @Override
                public void onScanResult(int i, byte[] bytes) {
                  if (i != -2001 || bytes != null) {
                    callbackContext.success(i + ":" + new String(bytes));
                    return;
                  } else {
                    try {
                      callbackContext.success("");
                    } catch (Exception e) {
                    }
                  }
                }
              });
            } catch (Exception e) {
            }
          } else {
            callbackContext.error("没有登陆");
            return;
          }
        }
      });
    } catch (Exception e) {
      callbackContext.error("硬件调用异常：" + e);
      return;
    }
  }


  private synchronized void checkLogin(final CallbackContext callbackContext) throws SdkException {
    BaseSystemManager.getInstance().deviceServiceLogin(this.cordova.getActivity(), null, "99999998", new OnServiceStatusListener() {
      @Override
      public void onStatus(int i) {
        if (0 == i || 2 == i || 100 == i) {
          isLogin = true;
        }
      }
    });
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    try {
      this.scannerManager.stopScan();
      BaseSystemManager.getInstance().deviceServiceLogout();
      isLogin = false;
    } catch (Exception e) {
    }
  }
}
